/*********************************************************************/
/*describe:this code fork a new process,one for the UI and the other for  recviving data
           the data is a 4 int number. define in car_info */
/*author:DocRun                         */
/* Sun May 31 10:14:31 2009   copyright-by ruanbanyong@gmail.com*/


#include <QtGui/QApplication>
#include "mainwindow.h"
//#include "chead.h"
 #include <QTextCodec>
/*
typedef struct
{
     int car_id; // 车号预定义传输的车号
     int car_place;//车在最近的站点
     int car_time_hour;//车到站时间
     int car_time_min;

} car_info;
*/
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));
    QFont font("Times",12,QFont::Normal,FALSE);
    a.setFont(font);
    a.setOverrideCursor(QCursor(Qt::BlankCursor));//hide the cursor
        //int msg[4] ={8,34,54,64};
     //   w.updateInfo(msg,4);
     //fork 一个子进程用于读取数据
     int fd_memfifo;
     car_infos *p_map;//共享缓冲区的地址
     int ret;
     int msg[4];
     int retval;
     int i;
     
     fd_memfifo = open(INMSG_PATH,O_RDWR);
     if(fd_memfifo == -1)
     {
          printf("open INMSG_PATH failed\n");

          return -1;

     }
     p_map = (car_infos*)mmap(NULL,sizeof(car_infos)*CARMAXNUM,PROT_READ|PROT_WRITE,
                             MAP_SHARED|MAP_ANONYMOUS,-1,0);
     if(p_map == NULL)
     {
	  printf("mmap failed\n");
	  return -1;
	  
     }
     

     //父进程用于发布数据，子进程获取数据
     ret = fork();
     if(ret < 0)
     {
          printf("fork error \n");
          return -1;

     }

     if(ret == 0)
     {
          pid_t oldppid,nowppid;
          oldppid = getppid();
          while(1)
          {
               retval =  read(fd_memfifo,(void*)msg,4*4);
               //i = msg[0]%10;//保证数值在10以内
	       //找到对应的行数据保存,
               for(i = 0; i< CARMAXNUM ;i++)
	       {
		    if( carNumToOrder[i] == msg[0])
			 break;
		    
	       }
	       //如果不是预定的数据就退出
	       if(i == CARMAXNUM)
		    continue;
	       
               if(retval == 16)
               {
                    //用读取来的数据更改共享区
                    memcpy(&(*(p_map+i)).car_id,&msg[0],4);
                    memcpy(&(*(p_map+i)).car_place,&msg[1],4);
                    memcpy(&(*(p_map+i)).car_time_hour,&msg[2],4);
                    memcpy(&(*(p_map+i)).car_time_min,&msg[3],4);

               }
	       //  qDebug() << "in child process comming msg[0]"<<msg[0];

              // qDebug() <<"ppid =%d"<<ppid;
               nowppid = getppid();
               if(nowppid != oldppid) //如果父进程退出则子进程也退出
                   exit(0);

          }

     }
     
     //主进程启动UI
     
    MainWindow w(0,p_map);
    // qDebug( "comming p_map = %x\n",p_map);
    w.show();

    return a.exec();

}
